package page.ineffable.phonedemo.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import page.ineffable.phonedemo.model.PhoneSimple;
import page.ineffable.phonedemo.service.PhoneService;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 手机服务接口实现
 *
 * @author lqs2
 * @date 2018/11/10, Sat
 */
public class PhoneServiceImpl implements PhoneService {


    /**
     * 日志打印
     */
    private static Logger log = LoggerFactory.getLogger(PhoneServiceImpl.class);

    /**
     * 源文件的路径，相对于resource路径
     */
    private static String filePath0 = "phone.data.txt";

    /**
     * 优化后的新文件，相对于项目目录，如果不存在请调用zipSourceFile()方法
     */
    private static String filePath1 = "data/phone.data.new.txt";

    /**
     * 优化后的文件映射
     */
    private static String filePath2 = "data/phone.data.map.txt";


    private static Map<String, PhoneSimple> phoneCache = new HashMap<>(1048576);
    private static Map<String, PhoneSimple> mapCache = new HashMap<>(512);

    static {
        try {
            loadFile();
        } catch (IOException e) {
            log.error("{}", "源文件加载失败");
            log.error("", e);
            System.exit(1);
        }
    }

    @Override
    public PhoneSimple onCall(String number) {
        PhoneSimple simple = phoneCache.get(number);
        if (simple == null) {
            return null;
        }
        PhoneSimple simple1 = mapCache.get(simple.getAbbr());
        String operator = simple.getOperator();
        simple1.setOperator("a".equals(operator) ? "中国移动" : ("b".equals(operator) ? "中国联通" : "中国电信"));
        simple1.setPhonePrefix(simple.getPhonePrefix());
        return simple1;
    }

    @Override
    public void zipSourceFile() throws IOException {

        InputStream ips0 = PhoneServiceImpl.class.getClassLoader().getResourceAsStream(filePath0);
        BufferedReader reader0 = new BufferedReader(new InputStreamReader(ips0), 10 * 1024 * 1024);

        // 临时用来去重
        Map<String, PhoneSimple> tempMap = new HashMap<>(512);

        OutputStream ops1 = new FileOutputStream(filePath1);
        BufferedWriter writer1 = new BufferedWriter(new OutputStreamWriter(ops1));
        OutputStream ops2 = new FileOutputStream(filePath2);
        BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(ops2));

        final char[] c1 = {'a'};
        final char[] c2 = {'a'};

        String line0;
        while ((line0 = reader0.readLine()) != null) {
            String[] fields = line0.split("\\s+");
            String s0 = fields[0];
            String s1 = fields[1];
            String s2 = fields[2];
            String s3 = fields[3];
            String s4 = fields[4];
            String s5 = fields[5];

            PhoneSimple simple = tempMap.get(s1 + s2);
            String flag;
            if (simple == null) {
                simple = new PhoneSimple();
                flag = String.valueOf(c1[0]) + String.valueOf(c2[0]);
                simple.setAbbr(flag);
                simple.setProvince(s1);
                simple.setCity(s2);
                simple.setCityCode(s4);
                simple.setPostCode(s5);
                if (c2[0] != 'z') {
                    c2[0]++;
                } else {
                    c2[0] = 'a';
                    c1[0]++;
                }
                tempMap.put(s1 + s2, simple);
                writer2.write(s1 + " " + s2 + " " + flag + " " + s4 + " " + s5);
                writer2.newLine();
            }
            writer1.write(s0 + " " + simple.getAbbr() + " " + ("中国移动".equals(s3) ? "a" : ("中国联通".equals(s3) ? "b" : "c")));
            writer1.newLine();
        }
        writer1.close();
        writer2.close();
    }

    /**
     * 加载对比文件到内存中
     **/
    private static void loadFile() throws IOException {
        InputStream ips = null;
        try {
            ips = new FileInputStream(filePath1);
        } catch (FileNotFoundException e) {
            log.error("未找到优化文件");
            log.error("", e);
            System.exit(1);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(ips), 6 * 1024 * 1024);
        String line;
        while ((line = reader.readLine()) != null) {
            String[] fields = line.split("\\s+");
            PhoneSimple simple = new PhoneSimple();
            simple.setAbbr(fields[1]);
            simple.setPhonePrefix(fields[0]);
            simple.setOperator(fields[2]);
            phoneCache.put(fields[0], simple);
        }
        InputStream ips1 = new FileInputStream(filePath2);
        BufferedReader reader2 = new BufferedReader(new InputStreamReader(ips1), 1024 * 1024);
        String line2;
        while ((line2 = reader2.readLine()) != null) {
            String[] fields = line2.split("\\s+");
            PhoneSimple simple = new PhoneSimple();
            simple.setAbbr(fields[2]);
            simple.setProvince(fields[0]);
            simple.setCity(fields[1]);
            simple.setCityCode(fields[3]);
            simple.setPostCode(fields[4]);
            mapCache.put(fields[2], simple);
        }
    }
}
